package com.david.reader.activity

import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.david.core.event.MyEventBus
import com.david.core.event.Subscribe
import com.david.core.event.ThreadMode
import com.david.reader.R
import com.david.reader.adapter.BookShellAdapter
import com.david.reader.adapter.OnBookItemClickListener
import com.david.reader.bean.BookBean
import com.david.reader.event.BookAddShellEvent
import com.david.reader.utils.BookHelper
import com.david.reader.utils.FileUtil
import com.david.reader.viewmodel.BookShellVm
import com.google.android.material.snackbar.Snackbar
import java.io.File


/**
 * 书架页面
 * TODO 调用系统文件选择器选择书籍；
 * TODO 使用MMKV缓存数据：https://blog.csdn.net/huangyuan_xuan/article/details/109459727
 *
 * 参照小米阅读：从文件管理处打开app，传入路径提示是否加入书架，不单独做选择文件了
 *
 * 获取所有文件权限（文件管理权限），然后读取documents中书籍，其他书籍移动到documents中才能识别
 *
 * txt书籍通过打开系统应用来阅读
 */
class BookShellActivity:AppCompatActivity(), OnBookItemClickListener {
    private lateinit var bookShellVm: BookShellVm
    private lateinit var adapter: BookShellAdapter

    private val startForResult = registerForActivityResult(ActivityResultContracts.GetContent()){
//        FileUtil.getFileRealNameFromUri(this, it)?.let {name ->  Log.e("name", name) }
//
//        FileUtil.copyFileToCache(applicationContext, it)
    }

    private val readResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()){
        it.data?.let { data ->
            adapter.notifyItemChanged(data.getIntExtra("position", 0))
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_book_shell)

        //android11管理所以文件：https://developer.android.google.cn/training/data-storage/manage-all-files?hl=zh-cn, https://juejin.cn/post/7012262477828194340
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            //检查是否已经有权限
            if (!Environment.isExternalStorageManager()) {
                //跳转新页面申请权限
                startActivityForResult( Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), 101);
            }
        }


        findViewById<View>(R.id.add).setOnClickListener {
//            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
////            intent.type = "video/*;image/*";//同时选择视频和图片
//            intent.type = "application/pdf"
//            intent.action = Intent.ACTION_GET_CONTENT
//            intent.addCategory(Intent.CATEGORY_OPENABLE)
////            intent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, pickerInitialUri);
//            startActivityForResult(intent, 0)


            //startForResult.launch("application/pdf")


            Snackbar.make(it.parent as ViewGroup, "pdf文件移动至documents文件夹中即可显示在列表", Snackbar.LENGTH_LONG).show();
        }


        bookShellVm = ViewModelProvider(this)[BookShellVm::class.java]
        val bookList = findViewById<RecyclerView>(R.id.book_list)
        bookList.let {

            it.layoutManager = GridLayoutManager(this, 3)
            adapter = BookShellAdapter()
            it.adapter = adapter

            adapter.onBookItemClickListener = this@BookShellActivity
        }

        bookShellVm.bookListData.observe(this) { books ->
            if (books != null) {
                adapter.datas = books
                adapter.notifyItemRangeInserted(0, books.size)
            }
        }

        bookShellVm.getData()

        MyEventBus.getDefault().register(this, "onBookAddShellEvent", BookAddShellEvent::class.java)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onBookAddShellEvent(event: BookAddShellEvent){
        bookShellVm.bookListData.value?.let { it ->
            it.map {
                if (it.bookName.equals(event.name) && it.bookName.equals(event.name) && it.type == event.type) {
                    return
                }
            }

            val id = System.currentTimeMillis().toString()

            it.add(0, BookBean(event.name, event.type, id))
            FileUtil.writeFileInfo(it)

            adapter.notifyItemInserted(0)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        MyEventBus.getDefault().unregister(this, "onBookAddShellEvent", BookAddShellEvent::class.java)
    }

    override fun onBookItemClick(position: Int, bookBean: BookBean) {
        if (bookBean.bookName?.endsWith(".txt") == true || bookBean.bookName?.endsWith(".TXT") == true) {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            val contentUri = FileProvider
                .getUriForFile(this, "com.david.reader", File(FileUtil.getDocumentsPath() +"/"+ bookBean.bookName))
            intent.setDataAndType(Uri.fromFile(File(FileUtil.getDocumentsPath() +"/"+ bookBean.bookName)), "text/plain")
            startActivity(intent)
            return
        }


        val intent = Intent(this, PdfReaderActivity::class.java)
        intent.putExtra("id", bookBean.id)
        intent.putExtra("name", bookBean.bookName)
        intent.putExtra("simpleName", bookBean.simpleName)
        intent.putExtra("type", bookBean.type)
        intent.putExtra("position", position)

        readResult.launch(intent)

        if (position > 0) {
            BookHelper.instance.bookList.remove(bookBean)
            BookHelper.instance.addItem(0, bookBean)
            adapter.notifyItemRangeChanged(0, position + 1)
        }
    }

    override fun onBookItemLongClick(position: Int, bookBean: BookBean) {
        AlertDialog.Builder(this).setMessage("删除本书？")
            .setNegativeButton("否", null)
            .setPositiveButton("是") { _, _ ->
                BookHelper.instance.removeItem(position)
                adapter.notifyDataSetChanged()//删除item后后面的view的tag要修改
            }.show()
    }



//    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        super.onActivityResult(requestCode, resultCode, data)
//        // TODO: 2022/1/1 直接加入书架
////        CommonUtils.getDocFilePathFromContentUri(data?.data, contentResolver)
////        findViewById<PDFView>(R.id.pdf_view).fromUri(data?.data).load()
////        选择文件之后判断类型及获取uri或path 跳转阅读页
////        CommonUtils.getFilePathFromContentUri()
//        FileUtil.getFileRealNameFromUri(this, data?.data)?.let { Log.e("name", it) }
//
//        //选中文件后复制到app缓存文档文件夹中（仿小米阅读）
//        data?.data?.let {
//            it.path?.let { path->
//                // TODO: 2022/4/5 支持txt文档
////                if (path.endsWith(".txt") || path.endsWith(".TXT")|| path.endsWith(".Txt")) {
////                    FileUtil.copyFileToCache(applicationContext, it, object :OnFileCopiedListener{
////                        override fun onFileCopy(name: String, path: String) {
//////                            TxtUtils.getPages()
////                            //每本书存到一个数据库中
////                               val dataBase =
////                                    TxtDataBase.getTxtDataBase(this@BookShellActivity, name.substring(0, name.lastIndexOf(".")))
////                            if (dataBase != null) {
////                                TxtUtils.getPages(dataBase, FileInputStream(path))
////                            }
////                        }
////
////                        override fun onCopyFailed(path: String) {
////
////                        }
////
////                    })
////                } else if(path.endsWith(".pdf") || path.endsWith(".PDF")) {
//                    FileUtil.copyFileToCache(applicationContext, it)
////                } else {
////                    Toast.makeText(this@BookShellActivity, "目前只支持阅读Txt与pdf文档。", Toast.LENGTH_LONG).show()
////                }
//            }
//
//        }
//    }
}